package com.dd.duu.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dc.base.domain.DPage;
import com.dd.dc.base.domain.DResult;
import com.dd.dc.entity.users.DCommonCode;
import com.dd.duu.service.CodeClient;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 数据字典表 前端控制器
 * </p>
 *
 * @author JueDream
 * @since 2021-03-05
 */
@Slf4j
@RestController
@RequestMapping("/code/c/")
@GlobalTransactional(rollbackFor = Exception.class) // 分布式事务seata
public class CommonCodeController {

    @Autowired
    CodeClient codeClient;

    @ApiOperation(value = "数据字典分页(父级/子级)")
    @PostMapping("/queryCodeList")
    public DResult<DPage<DCommonCode>> queryCodeList(@RequestParam Integer page, @RequestParam Integer limit, @RequestParam String type, @RequestParam String codeName){
        log.info("UserUi queryCodeList start ...");
        Page<DCommonCode> pages = codeClient.queryCodeList(page, limit, type, codeName);
        DPage<DCommonCode> codePage = DPage.to(pages);
        return DResult.of(codePage);
    }

    @Transactional
    @ApiOperation(value = "数据字典新增/更新")
    @PostMapping("/saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody DCommonCode commonCode){
        boolean flag = false;
        // 判断新增/更新
        if (Objects.isNull(commonCode.getCId())) {
            // 新增权限
            Integer cId = codeClient.insert(commonCode);
            if (cId > 0){
                flag = true;
            }
        }else{
            // 更新权限
            flag = codeClient.updateById(commonCode);
            // 删除子集
            flag = codeClient.deleteChild(commonCode.getCId());
        }
        // 重新新增
        List<DCommonCode> children = commonCode.getChildren();
        if (children.size() > 0) {
            flag = codeClient.saveBathChildCode(children);
        }
        return DResult.of(flag);
    }

    @Transactional
    @ApiOperation(value = "数据字典删除")
    @DeleteMapping("/deleteCode")
    public DResult deleteCode(@RequestParam Integer cId){
        boolean flag = codeClient.delete(cId);
        return DResult.of(flag);
    }

}
